package com.ruoyi.web.controller.agentfare;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jlx.distribution.api.Distribution;
import com.jlx.distribution.pojo.change.output.FlightChangeInfo;
import com.jlx.distribution.pojo.change.output.FlightChangeParam;
import com.jlx.distribution.pojo.common.ResponseBase;
import com.jlx.distribution.pojo.common.passenger.Contact;
import com.jlx.distribution.pojo.common.passenger.Passenger;
import com.jlx.distribution.pojo.common.passenger.TicketPassenger;
import com.jlx.distribution.pojo.common.segment.SearchFlightSegment;
import com.jlx.distribution.pojo.endorse.ChgDetailReq;
import com.jlx.distribution.pojo.endorse.ChgDetailRes;
import com.jlx.distribution.pojo.endorse.ChgPsgInfo;
import com.jlx.distribution.pojo.order.CreateOrderRequest;
import com.jlx.distribution.pojo.order.CreateOrderResponse;
import com.jlx.distribution.pojo.order.ServiceOrderNotifyInfo;
import com.jlx.distribution.pojo.payok.input.PayOkParam;
import com.jlx.distribution.pojo.payok.output.PayOkResult;
import com.jlx.distribution.pojo.payvalid.input.PayCheck;
import com.jlx.distribution.pojo.payvalid.input.PayValidParam;
import com.jlx.distribution.pojo.payvalid.output.PayValidResult;
import com.jlx.distribution.pojo.search.input.SearchCondition;
import com.jlx.distribution.pojo.search.input.SearchParam;
import com.jlx.distribution.pojo.search.input.Segment;
import com.jlx.distribution.pojo.search.output.FlightProduct;
import com.jlx.distribution.pojo.search.output.Product;
import com.jlx.distribution.pojo.search.output.SearchResult;
import com.jlx.distribution.pojo.ticket.input.TicketParam;
import com.jlx.distribution.pojo.verify.input.Verify;
import com.jlx.distribution.pojo.verify.input.VerifyParam;
import com.jlx.distribution.pojo.verify.output.AvCheckResult;
import com.jlx.distribution.pojo.verify.output.VerifyResult;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.pojo.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.OrderInfo;
import com.ruoyi.system.domain.RefundChangeInfo;
import com.ruoyi.system.service.IOrderInfoService;
import com.ruoyi.system.service.IRefundChangeInfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping(value = "/open")
public class AgentfareController {

    private static final Logger logger = LoggerFactory.getLogger(AgentfareController.class);

    @Autowired
    private Distribution distribution;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IRefundChangeInfoService refundChangeInfoService;

    @GetMapping (value = "/search")
    @ResponseBody
    public AfareSearchResult search(@RequestParam (required = true, value = "dptAirport") String dpt,
                                    @RequestParam(required = true, value = "arrAirport") String arr,
                                    @RequestParam(required = true) String date,
                                    @RequestParam(required = true) String domain) {
        logger.debug("open search request dpt-{}, arr-{}, date-{},domain-{}", dpt, arr, date, domain);
        long time = System.currentTimeMillis();
        try {
            if(redisCache.getCacheObject("price_switch")!=null){
                return new AfareSearchResult();
            }

           int days= DateUtils.getDayBetween(DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate()),DateUtils.dateTime(DateUtils.YYYY_MM_DD,date));
           if(days<3||days>30){
               return new AfareSearchResult();
           }
            String key=dpt+arr+date;
            SearchResult searchResult=redisCache.getCacheObject(key);
            /*if(searchResult==null){
                refreshCache(dpt, arr, date);
                return new AfareSearchResult();
            }*/
            if(searchResult==null){
                SearchParam searchParam=new SearchParam();
                SearchCondition searchCondition=new SearchCondition();
                searchParam.setSearchCondition(searchCondition);
                Segment segment=new Segment();
                segment.setDep(dpt);
                segment.setArr(arr);
                segment.setDate(date);
                segment.setTripType("OW");
                segment.setResultType("own");
                segment.setCarrier(Constants.CARRIER);
                searchCondition.setSegments(Lists.newArrayList(segment));
                searchParam.setContext(RequestContextUtil.buildDefaultContext());
                searchResult=distribution.search(searchParam);
                //return new AfareSearchResult();
            }
            AfareSearchResult result = convertAfareSearchResult(dpt, arr, date, key,searchResult);
            logger.debug("open search convert result {}", JSONObject.toJSONString(result));
            return result;
        } catch (Exception e) {
            logger.error("open search exception", e);
            return null;
        } finally {
        }
    }

    private AfareSearchResult convertAfareSearchResult(String dpt,String arr,String date,String key,SearchResult searchResult){
        if (searchResult == null|| searchResult.getSearchResponse()==null || CollectionUtils.isEmpty(searchResult.getSearchResponse().getFlightProductGroup())) {
            return null;
        }
        //redisCache.setCacheObject(key,searchResult,300, TimeUnit.SECONDS);
        AfareSearchResult afareSearchResult = new AfareSearchResult();
        afareSearchResult.setDptAirport(dpt);
        afareSearchResult.setArrAirport(arr);
        afareSearchResult.setDate(date);
        // 最新版本 改afare
        afareSearchResult.setVersion("1.0");

        List<AfareFlight> afareFlights = Lists.newArrayList();
        for (FlightProduct flightProduct : searchResult.getSearchResponse().getFlightProductGroup()) {
            try {
                String flightNum=flightProduct.getFlight().get(0).getFlightIndex();
                SearchFlightSegment segment= searchResult.getSearchResponse().getFlights().get(flightNum);
                for(String productKey:flightProduct.getProductList()){
                    Product product = searchResult.getSearchResponse().getProducts().get(productKey);
                    /*if(new BigDecimal(product.getAdult().getFlightPrice()).floatValue()<350){
                      continue;
                    }*/
                    AfareFlight afareFlight = new AfareFlight();
                    afareFlight.setDptTime(segment.getDptTime().replace(":", ""));
                    afareFlight.setArrTime(segment.getArrTime().replace(":", ""));
                    afareFlight.setCarrier(segment.getCarrier());
                    afareFlight.setCode(segment.getCode());
                    afareFlight.setSaleCabinCode(product.getCabin().get(0).getAdultCabin());
                    // cpc上浮，默认为0
                    afareFlight.setCpcSalePrice(Float.MAX_VALUE);
                    afareFlight.setCpaSalePrice(new BigDecimal(product.getAdult().getFlightPrice()).floatValue()-1);
                    afareFlight.setPrintPrice(new BigDecimal(product.getAdult().getPrintPrice()).floatValue());
                    afareFlight.setAgeLimit(null);
                    afareFlight.setPlaneType(segment.getPlaneType());
                    // 经停
                    afareFlight.setStops(segment.getStops());

                    afareFlight.setCodeShare(segment.getCodeShare());
                    afareFlight.setSeatsForSale(product.getCabin().get(0).getCabinQuantity());
                    afareFlight.setCpcRefundRule(null);
                    afareFlight.setCpcChangeRule(null);
                    afareFlight.setCpcAllowChange(false);
                    afareFlight.setCpcRefundRule(null);
                    afareFlight.setCpaChangeRule(null);
                    afareFlight.setCpaAllowChange(false);
                    afareFlight.setCpaType(0);
                    afareFlight.setMeal(segment.isMeal());
                    afareFlight.setChildTicket(false);
                    afareFlights.add(afareFlight);
                }
            } catch (Exception e) { // 有转化操作，避免单节点报价影响全局
                logger.error("open search convert agent flight result error.", e);
            }
        }
        afareSearchResult.setFlight(afareFlights);
        return afareSearchResult;


    }



    @RequestMapping(value = "/booking")
    @ResponseBody
    public AfareBookingResult booking(@RequestParam(required = true, value = "dptAirport") String dpt,
                                      @RequestParam(required = true, value = "arrAirport") String arr,
                                      @RequestParam(required = true, value = "date") String date,
                                      @RequestParam(required = true, value = "code") String airline,
                                      @RequestParam(required = true, value = "saleCabinCode") String cabin,
                                      @RequestParam(required = true, value = "domain") String clientId,
                                      @RequestParam(required = true, value = "salePrice") float salePrice) {
        logger.info("open booking request dpt-{}, arr-{}, date-{},airline-{},cabin-{},clientId-{},salePrice-{}", dpt, arr, date, airline,
                cabin, clientId, salePrice);
        long start = System.currentTimeMillis();
        try {
            String key=dpt+arr+date;
            SearchResult searchResult=redisCache.getCacheObject(key);
            if(searchResult==null){
                SearchParam searchParam=new SearchParam();
                SearchCondition searchCondition=new SearchCondition();
                searchParam.setSearchCondition(searchCondition);
                Segment segment=new Segment();
                segment.setDep(dpt);
                segment.setArr(arr);
                segment.setDate(date);
                segment.setCode(airline);
                searchCondition.setSegments(Lists.newArrayList(segment));
                searchParam.setContext(RequestContextUtil.buildDefaultContext());
                searchResult=distribution.search(searchParam);
            }

            if (searchResult == null|| searchResult.getSearchResponse()==null || CollectionUtils.isEmpty(searchResult.getSearchResponse().getFlightProductGroup())) {
                logger.info("booking search price null {}",key);
                refreshCache(dpt,arr,date);
                return null;
            }
            String productKey=matchProductKey(cabin,salePrice,searchResult,airline);
            if(StringUtils.isBlank(productKey)){
                logger.info("match price failed {}",key);
                refreshCache(dpt,arr,date);
                return null;
            }
            VerifyParam verifyParam=new VerifyParam();
            verifyParam.setContext(RequestContextUtil.buildDefaultContext());
            Verify verify=new Verify();
            verifyParam.setVerify(verify);
            verify.setProductId(productKey);
            VerifyResult verifyResult=distribution.verify(verifyParam);
            return convertAfareBookingResult(dpt,arr,date,key,salePrice,verifyResult);
        } catch (Exception e) {
            logger.error("booking Exception", e);
            return null;
        } finally {

        }
    }

    private String matchProductKey(String cabin,float salePrice,SearchResult searchResult,String code) {
        for (FlightProduct flightProduct : searchResult.getSearchResponse().getFlightProductGroup()) {
                String flightNum=flightProduct.getFlight().get(0).getFlightIndex();
                //SearchFlightSegment segment= searchResult.getSearchResponse().getFlights().get(flightNum);
             if(StringUtils.equals(flightNum,code)){
                 for(String productKey:flightProduct.getProductList()){
                     Product product = searchResult.getSearchResponse().getProducts().get(productKey);
                     if(StringUtils.equals(cabin,product.getCabin().get(0).getAdultCabin())){
                         return productKey;
                     }
                 }
             }
        }
            return null;
    }

    private void refreshCache(String dpt,String arr,String date){
        AsyncWorker.execute(() -> {
            redisCache.deleteObject(dpt+arr+date);
            SearchParam searchParam=new SearchParam();
            SearchCondition searchCondition=new SearchCondition();
            searchParam.setSearchCondition(searchCondition);
            Segment segment=new Segment();
            segment.setDep(dpt);
            segment.setArr(arr);
            segment.setDate(date);
            segment.setTripType("OW");
            segment.setResultType("own");
            segment.setCarrier(Constants.CARRIER);
            searchCondition.setSegments(Lists.newArrayList(segment));
            searchParam.setContext(RequestContextUtil.buildDefaultContext());
            SearchResult searchResult=distribution.search(searchParam);
            if(searchResult!=null&&searchResult.getSearchResponse()!=null&&CollectionUtils.isNotEmpty(searchResult.getSearchResponse().getFlightProductGroup())){
                redisCache.setCacheObject(dpt+arr+date,searchResult,Constants.CACHE_TIMEOUT, TimeUnit.SECONDS);
            }

            Map<String, Object> paramMap=Maps.newHashMap();
            paramMap.put("dptAirport",dpt);
            paramMap.put("arrAirport",arr);
            paramMap.put("date",date.replace("-",""));
            paramMap.put("domain","kya");
            paramMap.put("secretKey","a398e9b0-0446-420a-a98f-ec7805702511");
            /*logger.info("jlx refreshCache param : {}",JSONObject.toJSONString(paramMap));*/
            String response= HttpUtil.get("http://agentfare.jiulvxing.com/afare/refresh/cache",paramMap);
            /*logger.info("jlx refreshCache response : {}",response);*/
        });
    }

    private AfareBookingResult convertAfareBookingResult(String dpt,String arr,String date,String key,float salePrice,VerifyResult verifyResult){
        if(verifyResult==null||verifyResult.getStatus().getCode()!=0){
            logger.info("booking failed {}",key);
            refreshCache(dpt,arr,date);
            return null;
        }
        AfareBookingResult afareBookingResult = new AfareBookingResult();
        AvCheckResult avCheckResult=verifyResult.getAvCheckResults().get(0);
        afareBookingResult.setDptAirport(avCheckResult.getDepCode());
        afareBookingResult.setArrAirport(avCheckResult.getArrCode());
        afareBookingResult.setDate(avCheckResult.getDate());
        afareBookingResult.setSessionId(verifyResult.getBookingKey());

        AfareBookingItem afareBookingItem = new AfareBookingItem();
        afareBookingItem.setDptTime(avCheckResult.getDptTime());
        afareBookingItem.setArrTime(avCheckResult.getArrTime());
        afareBookingItem.setCarrier(avCheckResult.getCarrier());
        afareBookingItem.setCode(avCheckResult.getCode());
        afareBookingItem.setPrintPrice(new BigDecimal(verifyResult.getPriceResult().getAdult().getPrintPrice()).floatValue());
        afareBookingItem.setSaleCabinCode(avCheckResult.getCabin());
        float bookingPrice=new BigDecimal(verifyResult.getPriceResult().getAdult().getFlightPrice()).floatValue();
        afareBookingItem.setCpaSalePrice(bookingPrice-salePrice<=3?salePrice:bookingPrice);
        afareBookingItem.setCpcSalePrice(Float.MAX_VALUE);

        afareBookingItem.setAgeLimit(null);
        afareBookingItem.setCpaType(0);
        afareBookingItem.setPlaneType(avCheckResult.getPlaneType());
        afareBookingItem.setStops(NumberUtils.toInt(avCheckResult.getStops(),0));
        afareBookingItem.setCodeShare(avCheckResult.getCodeShare());
        afareBookingItem.setSeatsForSale(avCheckResult.getSeatCount());
        afareBookingItem.setCpaRefundRule(verifyResult.getTgqRule().getAdult().getRefundRule());
        afareBookingItem.setCpaChangeRule(verifyResult.getTgqRule().getAdult().getChangeRule());
        afareBookingItem.setCpaAllowChange(verifyResult.getTgqRule().getAdult().isAllowChange());
        afareBookingItem.setChildTicket(verifyResult.getPriceResult().getChild()==null?false:true);

        afareBookingResult.setFlight(Lists.newArrayList(afareBookingItem));
        afareBookingResult.setVersion("1.0");
        return afareBookingResult;
    }




    @RequestMapping(value = "/order", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AfareCreatePnrResponse createOrder(@RequestBody OrderCondition orderCondition) {
        long time = System.currentTimeMillis();
        try {
            if (orderCondition == null) {
                logger.warn("order condition is null");
                return null;
            }
            logger.info("open order request: {}", JSONObject.toJSONString(orderCondition));
            CreateOrderRequest request=new CreateOrderRequest();
            request.setBookingKey(orderCondition.getSessionId());
            request.setContext(RequestContextUtil.buildDefaultContext());
            List<Passenger> passengers=Lists.newArrayList();
            request.setPassengers(passengers);
            for(AFarePassenger aFarePassenger:orderCondition.getPassengers()){
                Passenger passenger=new Passenger();
                passenger.setName(aFarePassenger.getName());
                passenger.setBirthday(aFarePassenger.getBirthday());
                passenger.setCardType(aFarePassenger.getCardType());
                passenger.setCardNum(aFarePassenger.getCardNo());
                passenger.setContactMob(aFarePassenger.getContactMob());
                passenger.setAgeType(Integer.parseInt(aFarePassenger.getType()));
                passenger.setGender(aFarePassenger.getSexType());
                passengers.add(passenger);
            }
            Contact contact=new Contact();
            contact.setContactPhone(orderCondition.getContactPhone());
            contact.setContactName(orderCondition.getPassengers().get(0).getName());
            request.setContact(contact);
            CreateOrderResponse createOrderResponse=distribution.order(request);
            return convertAfareCreatePnrResponse(orderCondition,createOrderResponse);
        } catch (Exception e) {
            logger.error("order exception", e);
            return null;
        } finally {

        }
    }

    private AfareCreatePnrResponse convertAfareCreatePnrResponse(OrderCondition orderCondition,CreateOrderResponse createOrderResponse){
        if(createOrderResponse.getStatus().getCode()!=0){
            return null;
        }
        AfareCreatePnrResponse afareCreatePnrResponse=new AfareCreatePnrResponse();
        String pnr=generatePnr();
        for(int i=0;i<5;i++){
            OrderInfo orderInfo=new OrderInfo();
            orderInfo.setPnr(pnr);
            List<OrderInfo> orderInfos =orderInfoService.selectOrderInfoList(orderInfo);
            if(CollectionUtils.isEmpty(orderInfos)){
                break;
            }
            pnr=generatePnr();
        }
        afareCreatePnrResponse.setAdlPnr(pnr);
        afareCreatePnrResponse.setChPnr(createOrderResponse.getChPnr());
        afareCreatePnrResponse.setVersion("1.0");
        afareCreatePnrResponse.setKey(makeKey(afareCreatePnrResponse.getAdlPnr(),afareCreatePnrResponse.getChPnr()));
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setTotalPrice(new BigDecimal(orderCondition.getSegments().get(0).getTotalPrice()));
        orderInfo.setOuterOrderNo(createOrderResponse.getOrderNo());
        orderInfo.setPnr(afareCreatePnrResponse.getAdlPnr());
        orderInfo.setOuterTotalPrice(createOrderResponse.getTotalPrice());
        orderInfo.setCreateTime(new Date());
        orderInfoService.insertOrderInfo(orderInfo);
        return afareCreatePnrResponse;
    }

    /**
     * 加密POST KEY -- 目前只有运价直连使用这个key
     * @param adlPnr
     * @param chPnr
     * @return
     */
    public  String makeKey(String adlPnr,String chPnr) {
        StringBuilder builder = new StringBuilder();
        builder.append("05FE5B8F254CD696317ACA7E0D29ABFC");
        builder.append(adlPnr);
        if (StringUtils.isNotEmpty(chPnr)) {
            builder.append(chPnr);
        }
        return DigestUtils.md5Hex(builder.toString()).toUpperCase();
    }

    private String generatePnr(){
        String randomcode = "";
        // 用字符数组的方式随机
        String model = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] m = model.toCharArray();
        for (int j = 0; j < 6; j++) {
            char c = m[(int) (Math.random() * 36)];
            // 保证六位随机数之间没有重复的
            if (randomcode.contains(String.valueOf(c))) {
                j--;
                continue;
            }
            randomcode = randomcode + c;
        }
        return randomcode;
    }


    @RequestMapping(value = "/validate")
    @ResponseBody
    public AFareValidatePnrResult validate(@RequestBody AFareValidatePnrCondition aFareValidatePnrCondition) {
        long start = System.currentTimeMillis();
        try {
            if (aFareValidatePnrCondition == null) {
                logger.warn("pay validate condition is null");
                return null;
            }
            logger.info("open validate request: {}", JSONObject.toJSONString(aFareValidatePnrCondition));
            OrderInfo orderInfo=new OrderInfo();
            orderInfo.setPnr(aFareValidatePnrCondition.getAdlPnr());
            List<OrderInfo> orderInfos =orderInfoService.selectOrderInfoList(orderInfo);
            if(CollectionUtils.isEmpty(orderInfos)){
                return null;
            }
            PayValidParam payValidParam=new PayValidParam();
            payValidParam.setContext(RequestContextUtil.buildDefaultContext());
            PayCheck payCheck=new PayCheck();
            payValidParam.setPayCheck(payCheck);
            payCheck.setOrderNo(orderInfos.get(0).getOuterOrderNo());
            PayValidResult payValidResult = distribution.payValid(payValidParam);
            AFareValidatePnrResult aFareValidatePnrResult=new AFareValidatePnrResult();
            aFareValidatePnrResult.setCode(payValidResult.getStatus().getCode()==0);
            return aFareValidatePnrResult;
        } catch (Exception e) {
            logger.error("pay validate error", e);
            return null;
        } finally {

        }
    }


    @RequestMapping(value = "/pay")
    @ResponseBody
    public AFarePayCallbackResult pay(@RequestBody AFarePushPayCondition aFarePushPayCondition) {
        long start = System.currentTimeMillis();
        try {
            if (aFarePushPayCondition == null) {
                logger.warn("pay condition is null");
                return null;
            }
            logger.info("open pay request: {}", JSONObject.toJSONString(aFarePushPayCondition));
            OrderInfo orderInfo=new OrderInfo();
            orderInfo.setPnr(aFarePushPayCondition.getAdlPnr());
            List<OrderInfo> orderInfos =orderInfoService.selectOrderInfoList(orderInfo);
            if(CollectionUtils.isEmpty(orderInfos)){
                return null;
            }
            PayOkParam payOkParam=new PayOkParam();
            payOkParam.setContext(RequestContextUtil.buildDefaultContext());
            payOkParam.setOrderNo(orderInfos.get(0).getOuterOrderNo());
            payOkParam.setPayAmount(orderInfos.get(0).getOuterTotalPrice());
            PayOkResult payOkResult = distribution.payOk(payOkParam);
            AFarePayCallbackResult aFarePayCallbackResult = new AFarePayCallbackResult();
            aFarePayCallbackResult.setCode(payOkResult.getStatus().getCode()==0);
            aFarePayCallbackResult.setMsg(payOkResult.getStatus().getCode()==0?"success":"fail");
            aFarePayCallbackResult.setVersion("1.0");
            if(aFarePayCallbackResult.isCode()){
                try{
                    orderInfos.get(0).setOrderNo(aFarePushPayCondition.getOrderNo());
                    orderInfos.get(0).setUpdateTime(new Date());
                    orderInfoService.updateOrderInfo(orderInfos.get(0));
                }catch (Exception e){
                    logger.error("insert pay info error",e);
                }
            }
            return aFarePayCallbackResult;
        } catch (Exception e) {
            logger.error("pay error", e);
            return null;
        } finally {
        }
    }

    @RequestMapping(value = "/lines")
    @ResponseBody
    public String lines() {
        return Constants.AIRLINES;
    }


    /**
     *
     * 出票同步
     * @param ticketParam
     * @author jlx
     * @date 2021/10/12 14:08
     * @return java.lang.String
     */
    @RequestMapping(value = "/issue/ticket")
    @ResponseBody
    public ResponseBase issueTicket(@RequestBody TicketParam ticketParam) {
        long start = System.currentTimeMillis();
        try {
            if (ticketParam == null) {
                logger.warn("ticket condition is null");
                return null;
            }
            logger.info("open issueTicket request: {}", JSONObject.toJSONString(ticketParam));
            OrderInfo orderInfo=new OrderInfo();
            orderInfo.setOuterOrderNo(ticketParam.getTicketInfo().getOrderNo());
            List<OrderInfo> orderInfos =orderInfoService.selectOrderInfoList(orderInfo);
            if(CollectionUtils.isEmpty(orderInfos)){
                return null;
            }
            JLXIssueTicketNotiflyOrderDetail detail = transform(orderInfos.get(0).getOrderNo(),ticketParam.getTicketInfo().getTicketPassengers());
            JLXIssueTicketNotiflyOrderList list = new JLXIssueTicketNotiflyOrderList();
            list.getOrderDetail().add(detail);
            String body =  JaxbXmlUtil.convertToXml(list);
            Map<String, Object> paramMap= Maps.newHashMap();
            paramMap.put("user","kya");
            paramMap.put("pass","kya");
            paramMap.put("domain","kya");
            paramMap.put("orderdata",body);
            logger.info("ticket request: {}",JSONObject.toJSONString(paramMap));
            String response=HttpUtil.post("http://fuwu.jiulvxing.com/autoOta/orderUpdate",paramMap);
            logger.info("ticket response: {}",response);
            return ResponseBase.success();
        } catch (Exception e) {
            logger.error("ticket error", e);
            return ResponseBase.fail(-1,e.getMessage());
        } finally {
        }
    }

    private JLXIssueTicketNotiflyOrderDetail transform(String orderNo, List<TicketPassenger> ticketPassengers) throws Exception {
        JLXIssueTicketNotiflyOrderDetail orderDetail = new JLXIssueTicketNotiflyOrderDetail();
        orderDetail.setNo(orderNo);
        orderDetail.setStatus("1");
        for (TicketPassenger passengerInfo : ticketPassengers) {
            JLXIssueTicketNotiflyPassenger passenger = new JLXIssueTicketNotiflyPassenger();
            passenger.setCano(passengerInfo.getCardNum());
            passenger.setName(passengerInfo.getName());
            passenger.setNo(passengerInfo.getTickets().get(0).getTicketNo());
            orderDetail.getPassenger().add(passenger);
        }
        return orderDetail;
    }


    /**
     *
     * 改期同步
     * @param serviceOrderNotifyInfo
     * @author jlx
     * @date 2021/10/12 14:08
     * @return java.lang.String
     */
    @RequestMapping(value = "/service/notify")
    @ResponseBody
    public ResponseBase serviceNotify(@RequestBody ServiceOrderNotifyInfo serviceOrderNotifyInfo) {
        long start = System.currentTimeMillis();
        try {
            if (serviceOrderNotifyInfo == null) {
                logger.warn("serviceNotify condition is null");
                return null;
            }
            logger.info("open serviceNotify request: {}", JSONObject.toJSONString(serviceOrderNotifyInfo));
            //处理改期
            if(serviceOrderNotifyInfo.getServiceOrderType()==1&&serviceOrderNotifyInfo.getServiceOrderStatus()==13){
                RefundChangeInfo refundChangeInfo=new RefundChangeInfo();
                refundChangeInfo.setOuterOrderNo(serviceOrderNotifyInfo.getOrderNo());
                refundChangeInfo.setOuterServiceOrderId(ChangeOrderUtil.decodeServOrderId(serviceOrderNotifyInfo.getServiceOrderNo()));
                List<RefundChangeInfo> refundChangeInfos= refundChangeInfoService.selectRefundChangeInfoList(refundChangeInfo);
                if(CollectionUtils.isNotEmpty(refundChangeInfos)){
                    ChgDetailReq chgDetailReq=new ChgDetailReq();
                    chgDetailReq.setContext(RequestContextUtil.buildDefaultContext());
                    chgDetailReq.setOrderNo(serviceOrderNotifyInfo.getServiceOrderNo());
                    ChgDetailRes chgDetailRes = distribution.queryChangeDetail(chgDetailReq);
                    JSONObject data=new JSONObject();
                    JSONObject ticketNums=new JSONObject();
                    data.put("orderNo",refundChangeInfos.get(0).getOrderNo());
                    data.put("servOrderId",refundChangeInfos.get(0).getServiceOrderId());
                    data.put("ticketNums",ticketNums);
                    for(ChgPsgInfo chgPsgInfo:chgDetailRes.getChangePassengerList()){
                        ticketNums.put(chgPsgInfo.getName(),chgPsgInfo.getTickets().get(0).getTicketNo());
                    }

                    Map<String, Object> paramMap= Maps.newHashMap();
                    paramMap.put("user","kya");
                    paramMap.put("pass","kya");
                    paramMap.put("domain","kya");
                    paramMap.put("data",data.toJSONString());
                    logger.info("changeUpdate request: {}",JSONObject.toJSONString(paramMap));
                    String response=HttpUtil.post("http://fuwu.jiulvxing.com/autoOta/changeUpdate",paramMap);
                    logger.info("changeUpdate response: {}",response);
                }
            }
            return ResponseBase.success();
        } catch (Exception e) {
            logger.error("serviceNotify error", e);
            return ResponseBase.fail(-1,e.getMessage());
        } finally {
        }
    }

    /**
     *
     * 航变同步
     * @param flightChangeParam
     * @author jlx
     * @date 2021/10/12 14:08
     * @return java.lang.String
     */
    @RequestMapping(value = "/flight/change")
    @ResponseBody
    public ResponseBase flightChange(@RequestBody FlightChangeParam flightChangeParam) {
        long start = System.currentTimeMillis();
        try {
            if (flightChangeParam == null) {
                logger.warn("flightChange condition is null");
                return null;
            }
            logger.info("open flightChange request: {}", JSONObject.toJSONString(flightChangeParam));
            //处理改期
            for (FlightChangeInfo flightChangeInfo :flightChangeParam.getChanges()){
                OrderInfo orderInfo=new OrderInfo();
                orderInfo.setOuterOrderNo(flightChangeInfo.getOrderNo());
                List<OrderInfo> orderInfos =orderInfoService.selectOrderInfoList(orderInfo);
                if(CollectionUtils.isEmpty(orderInfos)){
                    continue;
                }

                JSONObject change=new JSONObject();
                change.put("orderNo",orderInfos.get(0).getOrderNo());
                change.put("flightChangeType",flightChangeInfo.getFlightChangeType().code);
                change.put("preDptDate",flightChangeInfo.getPreDptDate());
                change.put("preArrDate",flightChangeInfo.getPreArrDate());
                change.put("preFlightNo",flightChangeInfo.getPreFlightNo());
                change.put("preDptAirport",flightChangeInfo.getPreDptAirport());
                change.put("preArrAirport",flightChangeInfo.getPreArrAirport());
                change.put("preDptTime",flightChangeInfo.getPreDptTime());
                change.put("preArrTime",flightChangeInfo.getPreArrTime());
                change.put("preDptTower",flightChangeInfo.getPreDptTerminal());
                change.put("preArrTower",flightChangeInfo.getPreArrTerminal());
                if(StringUtils.equals(flightChangeInfo.getFlightChangeType().code,"CHANGE")){
                    change.put("folDptDate",flightChangeInfo.getFolDptDate());
                    change.put("folArrDate",flightChangeInfo.getFolArrDate());
                    change.put("folFlightNo",flightChangeInfo.getFolFlightNo());
                    change.put("folDptAirport",flightChangeInfo.getFolDptAirport());
                    change.put("folArrAirport",flightChangeInfo.getFolArrAirport());
                    change.put("folDptTime",flightChangeInfo.getFolDptTime());
                    change.put("folArrTime",flightChangeInfo.getFolArrTime());
                    change.put("folDptTower",flightChangeInfo.getFolDptTerminal());
                    change.put("folArrTower",flightChangeInfo.getFolArrTerminal());
                }
                    Map<String, Object> paramMap= Maps.newHashMap();
                    paramMap.put("user","kya");
                    paramMap.put("pass","kya");
                    paramMap.put("domain","kya");
                    paramMap.put("data",change.toJSONString());
                    logger.info("flightChange request: {}",JSONObject.toJSONString(paramMap));
                    String response=HttpUtil.post("http://fuwu.jiulvxing.com/autoOta/flightChange",paramMap);
                    logger.info("flightChange response: {}",response);
            }
            return ResponseBase.success();
        } catch (Exception e) {
            logger.error("flightChange error", e);
            return ResponseBase.fail(-1,e.getMessage());
        } finally {
        }
    }

    @GetMapping (value = "/close/price")
    @ResponseBody
    public String closePrice() {
          redisCache.setCacheObject("price_switch","true");
          return "success";
    }

    @GetMapping (value = "/open/price")
    @ResponseBody
    public String openPrice() {
        redisCache.deleteObject("price_switch");
        return "success";
    }

    @GetMapping (value = "/get/redis")
    @ResponseBody
    public String redis(String key) {
        return redisCache.getCacheObject(key);
    }


    @GetMapping (value = "/close/ziyuan/refund/syn")
    @ResponseBody
    public String closeRefund() {
        redisCache.setCacheObject("ziyuan_refund","true");
        return "success";
    }

    @GetMapping (value = "/open/ziyuan/refund/syn")
    @ResponseBody
    public String openRefund() {
        redisCache.deleteObject("ziyuan_refund");
        return "success";
    }

    @GetMapping (value = "/set/refund/amount/limit")
    @ResponseBody
    public String setRefundLimit(String amount) {
        redisCache.setCacheObject("refund_amount_limit",amount);
        return "success";
    }

}
